﻿using LitJson;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace FrameWorkSong
{
    public enum LoadState
    {
        Waiting,
        Loaded
    }
    public class HotUpdateManagers : Singleton<HotUpdateManagers>
    {
        LoadState my_UpdateState;
        LoadState My_UpdateState
        {
            get { return my_UpdateState; }
            set
            {
                my_UpdateState = value;
                if (my_UpdateState== LoadState.Loaded)
                {
                    GetDescribe("加载资源");
                    if (my_AssetBundleAction!=null)
                    {
                        ToloadAssetBundle(my_AssetBundleAction);
                    }
                    if (my_FileAction!=null)
                    {
                        ToloadAsset(my_FileAction);
                    }
                }
            }
        }
        Dictionary<string,string> my_VersionInfos;
        FileMgr fileMgr;
        HttpRequest httpRequest;
        ResLoader resLoader;

        string my_CurAssetName;
        string my_CurVersion;
        string my_CurDownloadUrl;
        Action<AssetBundle> my_AssetBundleAction;
        Action my_FileAction;
        Action<string> my_Describe;
        Action<float> my_Progree;
        public override void OnBeforeDestroy(){ }
        void Awake()
        {
            fileMgr = FileMgr.Instance;
            httpRequest = HttpRequest.Instance;
            resLoader = new ResLoader();
            ReadVersionInfo();
        }
        /// <summary>
        /// 更新AssetBundle
        /// </summary>
        /// <param name="assetName">资源名称</param>
        /// <param name="version">资源版本</param>
        /// <param name="downloadUrl">下载地址</param>
        /// <param name="asset">返回资源方法</param>
        /// <param name="describe">返回描述方法</param>
        /// <param name="progree">返回进度方法</param>
        public void FromAssetBundle(string assetName, string version, string downloadUrl, Action<AssetBundle> asset, Action<String> describe=null, Action<float>progree=null)
        {
            my_FileAction = null;
            my_AssetBundleAction = asset;
            my_Describe = describe;
            my_Progree = progree;
            HotUpdate(assetName, version, downloadUrl);
        }
        /// <summary>
        /// 更新文件
        /// </summary>
        /// <param name="assetName">资源名称</param>
        /// <param name="version">资源版本</param>
        /// <param name="downloadUrl">下载地址</param>
        /// <param name="asset">返回资源方法</param>
        /// <param name="describe">返回描述方法</param>
        /// <param name="progree">返回进度方法</param>
        public void FromFile(string assetName, string version, string downloadUrl, Action asset, Action<String> describe = null, Action<float> progree = null)
        {
            my_AssetBundleAction = null;
            my_FileAction = asset;
            my_Describe = describe;
            my_Progree = progree;
            HotUpdate(assetName, version, downloadUrl);
        }
        void HotUpdate(string assetName, string version, string downloadUrl)
        {
            My_UpdateState = LoadState.Waiting;
            my_CurAssetName = assetName;
            my_CurVersion = version;
            my_CurDownloadUrl = downloadUrl;
            if (version=="")
            {
                GetDescribe("资源更新");
                DownloadAsset();
            }
            else
            {
                if (IsNewVersion())
                {
                    GetDescribe("发现新版本，资源需要更新");
                    DownloadAsset();
                }
                else
                {
                    My_UpdateState = LoadState.Loaded;
                }
            }
        }

        /// <summary>
        /// 阅读本地版本信息
        /// </summary>
        void ReadVersionInfo()
        {
            my_VersionInfos = new Dictionary<string, string>();
            string jsonInfo= fileMgr.StrFileRead(fileMgr.PersistentPath, "VersionInfo.txt");
            if (jsonInfo!="")
            {
                JsonData jsonData = JsonMapper.ToObject(jsonInfo);
                for (int i = 0; i < jsonData.Count; i++)
                {
                    my_VersionInfos.AddData(jsonData[i]["AssetName"].ToString(), jsonData[i]["Version"].ToString());
                }
            }
        }
        /// <summary>
        /// 是否是新的版本
        /// </summary>
        /// <param name="assetName"></param>
        /// <param name="assetVersion"></param>
        /// <returns></returns>
         bool IsNewVersion()
        {
            if (!my_VersionInfos.ContainsKey(my_CurAssetName))
            {
                return true;
            }
            else
            {
                string oldVersionInfos = my_VersionInfos[my_CurAssetName];
                if (oldVersionInfos== my_CurVersion)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        /// <summary>
        /// 下载资源
        /// </summary>
        /// <param name="assetName"></param>
        /// <param name="DownloadUrl"></param>
        void DownloadAsset()
        {
            httpRequest.DownloadData(my_CurDownloadUrl, SaveAsset, GetProgree);
        }
        /// <summary>
        /// 保存资源
        /// </summary>
        /// <param name="data"></param>
        void SaveAsset(object data)
        {
            byte[] bytes = (byte[])data;
            fileMgr.SaveAssetFile(fileMgr.PersistentPath, my_CurAssetName, bytes);
            My_UpdateState = LoadState.Loaded;
            WriteVersionInfo();// 重写本地版本信息
        }
        /// <summary>
        /// 加载AssetBundle资源
        /// </summary>
        void ToloadAssetBundle(Action<AssetBundle> action)
        {
            //加载时如果本地没有该文件，重新下载
            if (fileMgr.IsHaveFile(fileMgr.PersistentPath, my_CurAssetName))
            {
                resLoader.LoadAssetAsync<AssetBundle>(my_CurAssetName, fileMgr.PersistentPath + my_CurAssetName, asset => { action(asset); });
            }
            else
            {
                FromAssetBundle(my_CurAssetName, "", my_CurDownloadUrl, my_AssetBundleAction, my_Describe, my_Progree);
            }
           
        }
        void ToloadAsset(Action action)
        {
            //加载时如果本地没有该文件，重新下载
            if (fileMgr.IsHaveFile(fileMgr.PersistentPath, my_CurAssetName))
            {
                action();
            }
            else
            {
                FromFile(my_CurAssetName, "", my_CurDownloadUrl, my_FileAction, my_Describe, my_Progree);
            }
            
        }
        /// <summary>
        /// 重写本地版本信息
        /// </summary>
        void WriteVersionInfo()
        {
            if (my_CurVersion!="")
            {
                my_VersionInfos.AddData(my_CurAssetName, my_CurVersion);
                int length = my_VersionInfos.Count;
                foreach (var item in my_VersionInfos)
                {
                    JsonUtil.AddData("AssetName", item.Key);
                    JsonUtil.AddData("Version", item.Value);
                    JsonUtil.AddDatas();
                }
                string info = JsonUtil.GetJsonStrings();
                fileMgr.StrFileWrite(fileMgr.PersistentPath, "VersionInfo.txt", info);
            }
        }

        void GetProgree(float progree)
        {
            if (my_Progree!=null)
            {
                my_Progree(progree);
            }
        }
        void GetDescribe(string describe)
        {
            if (my_Describe != null)
            {
                my_Describe(describe);
            }
        }
    }
}